package concurrencyPractice.chapter03;

import jdk.jfr.Event;

import java.util.Collection;
import java.util.EventListener;
import java.util.SortedSet;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序3-8使用工厂方法防止this引用在构造中溢出
 * @date 2023/12/27 10:04:12
 */
public class SafeListener {

    private final EventListener listener;

    private SafeListener() {

        listener = new EventListener() {
            public void onEvent(Event e) {
                // doSomething(e)
            }
        };
    }

    public static  SafeListener newInstance(EventSource source) {
        SafeListener safe = new SafeListener();
        source.registerListener(safe.listener);

        return safe;
    }


    class EventSource {
        public void registerListener (EventListener safeListener) {

        }
    }

    class Animal {
        boolean isPotentialMate (Animal animal) {}
    }

    /**
     * 程序3-9 基本类型的局部变量和线程封闭性
     * @param candidates
     * @return
     */
    public int loadTheArt (Collection<Animal> candidates) {
        SortedSet<Animal> animals;
        int numPairs = 0;
        Animal candidate = null;

        animals = new SortedSet<Animal>(new SpeciesGenderComparator());
        animals.addAll(candidates);
        for (Animal a: animals
             ) {
            if(candidate == null || !candidate.isPotentialMate(a)) {
                candidate =a;
            }else {
                ark.load(new AnimaPair(candidate, a));
                ++ numPairs;
                candidate = null;
            }
        }

        return numPairs;
    }
}


